package com.supplychainapi.controller;

import com.supplychainapi.common.ApiVersion;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.domain.LoginCache;
import com.supplychainapi.domain.phone.LoginEntity;
import com.supplychainapi.model.Tbuser;
import com.supplychainapi.service.TbshopService;
import com.supplychainapi.service.TbuserService;
import com.supplychainapi.utils.CommonUtil;
import com.supplychainapi.utils.JwtUtil;
import com.supplychainapi.utils.MD5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理接口
 */
@RestController
@RequestMapping("/phone/{version}/user")
@Api(value = "UserController", description = "用户管理")
public class UserController {
    @Autowired
    private TbuserService tbuserService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbshopService tbshopService;


    @ApiOperation(httpMethod = "POST", value="登录", notes="swagger参数标识，用户登录接口,使用商户号或者商户名和账号密码登录")
    @ApiVersion(1)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "fsShopName", value = "手机号;swagger", required = true, dataType = "String", defaultValue = "系统商"),
            @ApiImplicitParam(paramType="query", name = "fsUserId", value = "账号;swagger", required = true,  dataType = "String", defaultValue = "admin"),
            @ApiImplicitParam(paramType="query", name = "fsPwd", value = "密码;swagger", required = true,  dataType = "String", defaultValue = "123456")
    })
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public RestResponse<Map<String, String>> login(@ApiIgnore @RequestBody LoginEntity login, HttpServletResponse response) throws ServletException {

        String jwtToken = "";

        if (StringUtils.isBlank(login.getFsShopName()) || StringUtils.isBlank(login.getFsPwd()) || StringUtils.isBlank(login.getFsUserId())) {
            return RestResponse.fail("登录失败，请检查商户名，账号，密码是否填写");
        }

        // 店铺名称或者店铺shopId
        String fsShopName = login.getFsShopName();

        // 账号名称
        String fsUserId = login.getFsUserId();

        // 密码
        String fsPwd = login.getFsPwd();

        // 查询店铺是否存在
        String fsShopGUID = tbshopService.selectByShopIdOrShopName(fsShopName);
        if (fsShopGUID == null) {
            return RestResponse.fail(400, "登录失败，请检查商户名，账号，密码是否正确");
        }

        // 查询用户是否存在
        Tbuser selectUser = new Tbuser();
        selectUser.setFsUserId(fsUserId);
        selectUser.setFsShopGUID(fsShopGUID);
        Tbuser user = tbuserService.findOne(selectUser);

        if (user == null) {
            return RestResponse.fail(400, "登录失败，请检查商户名，账号，密码是否正确");
        }

        String pwd = user.getFsPwd();

        if (!pwd.equals(MD5Utils.MD5Encode(fsPwd))) {
            return RestResponse.fail(400, "登录失败，请检查商户名，账号，密码是否正确");
        }

        try {
            String subject = jwtUtil.generalSubject(user);
            jwtToken = jwtUtil.createJWT(subject);
        } catch (Exception e) {
            throw new ServletException("创建token失败，请重试登录");
        }

        String token = CommonUtil.getToken(jwtToken, "PHONE");
        // 登录信息缓存
        tbuserService.LoginCache(fsShopGUID, token, user);

        Map<String, String> result = new HashMap<String, String>();
        result.put("token", jwtToken);

        return RestResponse.success(result, "登录成功");
    }
    @ApiVersion(1)
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public RestResponse<String> loginTest(HttpServletRequest request, HttpServletResponse response, @ApiIgnore LoginCache loginCache) throws ServletException {
        return RestResponse.success( "登录成功");
    }
}